package com.ruiyi.controller;

import com.ruiyi.common.Constants;
import com.ruiyi.common.UploadBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/download")
public class DownloadController {

    @Autowired
    private UploadBean uploadBean;

    //拷贝默认图片到服务器所指定的位置
    //D:/devTools/upload该路径里面如果已经有默认图片了，那么就不需要在拷贝；如果没有默认图片，则需要拷贝进来
    /*
    * @ModelAttribute主要的作用是将数据添加到对应的路径中去，最终用于页面的显示
    * 该注解用在方法上，被这个注解定义过的方法会在controller层里面的每一个方法执行前被调用
    * */
    @ModelAttribute
    public void transferDefaultImg(HttpServletRequest request) throws IOException {
        //获取到默认图片存放的文件夹目录
        String saveDirPath = uploadBean.getBaseUrl();
        //如果默认图片已经存在，则不执行拷贝图片的任务  D:/devTools/upload/default.png
        File file1 = new File(saveDirPath + "/" + Constants.DEFAULT_HEAD_IMG);
        if(file1.exists()){
            return;
        }
        //文件夹如果不存在，则需要创建
        File file2 = new File(saveDirPath);
        if(!file2.exists()){
            file2.mkdirs();
        }
        ServletContext application = request.getSession().getServletContext();
        //没有这个默认图片，就拷贝该默认图片进来
        String sourcePath = application.getRealPath("/resources/images/" + Constants.DEFAULT_HEAD_IMG);
        FileInputStream fis = new FileInputStream(sourcePath);
        //根据D:/devTools/upload/default.png图片路径去下载该图片
        FileOutputStream fos = new FileOutputStream(saveDirPath + "/" + Constants.DEFAULT_HEAD_IMG);
        byte[] bt = new byte[1024];
        int len = -1;
        //fis.read(bt)使用输入流通过字节去读要下载的图片的路径
        while((len = fis.read(bt)) != -1){
            //下载
            fos.write(bt,0,len);
        }
        fis.close();
        fos.close();
    }

    //头像的下载
    @RequestMapping("/downloadImg.do")
    public void downloadImg(String imgUrl, HttpServletResponse response) throws IOException {
        if(imgUrl != null){
            String saveDirPath = uploadBean.getBaseUrl();
            //D:/devTools/upload/default.png
            FileInputStream fis = new FileInputStream(saveDirPath + "/" + imgUrl);
            ServletOutputStream fos = response.getOutputStream();
            byte[] bt = new byte[1024];
            int len = -1;
            //fis.read(bt)使用输入流通过字节去读要下载的图片的路径
            while((len = fis.read(bt)) != -1){
                //下载
                fos.write(bt,0,len);
            }
            fis.close();
            fos.close();
        }
    }

}
